//
//  HomeTableViewController.swift
//  weibo117
//
//  Created by 宋禹奇 on 15/6/23.
//  Copyright © 2015年 宋禹奇. All rights reserved.
//

import UIKit
import SVProgressHUD

class HomeTableViewController: BaseTableViewController,StatusCellDelegate {
    
    //表格绑定的微博数据数组
    var statusesList: [Status]? {
        didSet {
            //刷新表格
            tableView.reloadData()
            //关闭刷新
            refreshControl?.endRefreshing()
        }
    }

    override func viewDidLoad() {
        super.viewDidLoad()

    visitorView?.setUpViewInfo("visitordiscover_feed_image_house", message: "关注一些人，回这里看看有什么惊喜", isHome: true)
    
        //如果用户没有登录直接返回
        if !userLogin {
            return
        }
        
        setUpNavigationBar()
        prepareTableView()
        prepareRefresh()
        
    }
    
    
    //加载微博数据
    func loadData(){
        //开始刷新,不会触发监听方法,会显示刷新空间
        refreshControl?.beginRefreshing()
        
        //下拉刷新的代号，取到数组中第1条数据的 id
        var since_id = statusesList?.first?.id ?? 0
        

        //上拉刷新代号,取到数组中第一个数据的id
        var max_id = 0
        if pullRefreshFlag {
            since_id = 0
            max_id = statusesList?.last?.id ?? 0
        }
        
        Status.loadStatus(since_id, max_id: max_id) { (statuses,error) -> () in
            //关闭刷新空间
            self.refreshControl?.endRefreshing()
            
            if error != nil {
                //提示用户网络不给力
                SVProgressHUD.showInfoWithStatus("您的网络不给力哦")
                return
            }
            if statuses == nil {
                print("没有数据")
                return
            }
            
            // 跟踪转发微博
            print("加载了 \(statuses?.count) 条微博")
            
            // 判断是否是下拉刷新，将新的数据，添加到原有数组的前面
            if since_id > 0 {
                self.statusesList = statuses! + self.statusesList!
            }else if max_id > 0 {
                self.statusesList = self.statusesList! + statuses!
                self.pullRefreshFlag = false
                
            }else{
                //初始刷新
                self.statusesList = statuses

            }
            
        }
    }
    
    //MARK: 数据源方法
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return statusesList?.count ?? 0
    }
    
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        //获取模型
        let status = statusesList![indexPath.row]
        
        //取重用标示符
        let ID = StatusCell.cellIdentifier(status)
        
        let cell = tableView.dequeueReusableCellWithIdentifier(ID, forIndexPath: indexPath) as! StatusCell
        
        cell.photoDelegate = self
        
        cell.status = status

        //判断是否为最后一行
        if indexPath.row == statusesList!.count - 1 {
        
            pullRefreshFlag = true
            //刷新数据
            loadData()
        
        }
        
        return cell
        
    }
    //定义行高缓存
    lazy var rowHeightCache = [Int: CGFloat]()
    
    override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        //取到对象
        let status = statusesList![indexPath.row]
        //判断是否缓存了行高,如果有直接返回
        if rowHeightCache[status.id] != nil {
           // print("返回缓存行高...")
            return rowHeightCache[status.id]!
        }
        // 2. 获取 cell － 从可重用的 缓冲池 中提取一个cell，说明之前用过，要计算行高准确，需要实例化一个cell
        // Xcode 7.0 新发现的
        // 2.1 取可重用的 ID
        let ID = StatusCell.cellIdentifier(status)
        // 2.2 定义一个类，默认是原创微博的 cell
        var cls:AnyClass = StatusNormalCell.self
        // 2.3 根据 ID 判断是否是转发微博
        if ID == YUStatusForwardCellIdentifier {
            cls = StatusForwardCell.self
        }
        // 2.4 根据 cls 创建 cell
        let cell = cls.new() as! StatusCell
       
//        //获取cell
//        let cell = tableView.dequeueReusableCellWithIdentifier(StatusCell.cellIdentifier(status)) as! StatusCell
        
        //返回行高
        let height = cell.rowHeight(status)
        rowHeightCache[status.id] = height
        return height
        
    }
    
    func statusCellDidSelectedPhoto(cell: StatusCell, photoIndex: Int) {
        print(cell.status!.largePicURLs![photoIndex])
        if cell.status?.largePicURLs == nil {
            return
        }
        //传递数据  图像的数组 & 用户选中的照片索引
        let vc = PhotoBrowserViewController(urls: cell.status!.largePicURLs!, index: photoIndex)
        presentViewController(vc, animated: true, completion: nil)
    }
    
    
    let popoverAnimator = PopoverAnimator()
    
    //下拉朋友圈按钮
    func titleButtonClicked(){
        //加载sb
        let sb = UIStoryboard(name: "FriendGroup", bundle: nil)
        let vc = sb.instantiateViewControllerWithIdentifier("FriendGroupSB")
        
        vc.transitioningDelegate = popoverAnimator
        
        let x = (view.bounds.width - 200) * 0.5
        popoverAnimator.presentFrame = CGRectMake(x, 56, 200, 300)
        
        //设施转场动画的模式,自定义转成动画
        vc.modalPresentationStyle = UIModalPresentationStyle.Custom
        
        presentViewController(vc, animated: true, completion: nil)
    
    }
    
    // MARK: 设置 ui
    //设置导航条
    private func setUpNavigationBar(){
    
        if sharedUserAccount == nil{
        
            return
        }
        
        let leftBtn = UIButton()
        
        leftBtn.frame = CGRectMake(0, 0, 30, 30)
        leftBtn.setImage(UIImage(named: "navigationbar_friendsearch"), forState: UIControlState.Normal)
        leftBtn.setImage(UIImage(named: "navigationbar_friendsearch_highlighted"), forState: UIControlState.Highlighted)
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(customView: leftBtn)
        
        let rightBtn = UIButton()
        rightBtn.frame = CGRectMake(0, 0, 30, 30)
        rightBtn.setImage(UIImage(named: "navigationbar_pop"), forState: UIControlState.Normal)
        rightBtn.setImage(UIImage(named: "navigationbar_pop_highlighted"), forState: UIControlState.Highlighted)
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(customView: rightBtn)
        
        let name = sharedUserAccount!.name!
        
        let titleButton = HomeTitleButton()
        
        titleButton.frame = CGRectMake(0, 0, 60, 30)
        titleButton.setTitleColor(UIColor.blackColor(), forState: UIControlState.Normal)
        titleButton.titleLabel?.font = UIFont.systemFontOfSize(17.0)
        titleButton.setTitle(name + "  ", forState: UIControlState.Normal)
        titleButton.setImage(UIImage(named: "navigationbar_arrow_down"), forState: UIControlState.Normal)
        
        titleButton.addTarget(self, action: "titleButtonClicked", forControlEvents: UIControlEvents.TouchUpInside)
        
        navigationItem.titleView = titleButton
        
        
    
    }
    
    //准备tableView
    private func prepareTableView() {
        
        //注册转发微博重用标示符
        tableView.registerClass(StatusForwardCell.self, forCellReuseIdentifier: YUStatusForwardCellIdentifier)
        //注册原创微博重用标示符
        tableView.registerClass(StatusNormalCell.self, forCellReuseIdentifier: YUStatusNormalCellIdentifier)
        
        //tableView.estimatedRowHeight = 200
        //tableView.rowHeight = 300
        tableView.separatorStyle = UITableViewCellSeparatorStyle.None
        
        //  tableView.rowHeight = UITableViewAutomaticDimension

    }

    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)
        //开始动画
        visitorView?.startAnimation()
    }
    
    //内存警告清空缓存行高
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        rowHeightCache.removeAll()
    }
    
    //准备刷新
    private func prepareRefresh() {
        //刷新控件
        refreshControl = YURefreshControl()
        
        //添加监听方法
        refreshControl?.addTarget(self, action: "loadData", forControlEvents: UIControlEvents.ValueChanged)
        //加载数据
        loadData()
        
        
    }

    /// 上拉刷新标记
    private var pullRefreshFlag = false

}








